package com.demo;

import io.appium.java_client.AppiumDriver;
import io.appium.java_client.TouchAction;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

/**
 * Created by Administrator on 2017/7/7.
 */
public class Finder {

    private AppiumDriver<WebElement> driver;
    public static int DEFAULT_TIMEOUT = 10;

    public Finder(AppiumDriver driver){
        this.driver = driver;
    }

    public WebElement findById(String id){
        WebDriverWait wait = new WebDriverWait(driver,DEFAULT_TIMEOUT);
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(id)));
        return driver.findElement(By.id(id));
    }

    public WebElement findById(String id,int index){
        WebDriverWait wait = new WebDriverWait(driver,DEFAULT_TIMEOUT);
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(id)));
        return driver.findElements(By.id(id)).get(index);
    }

    public WebElement findByText(String text){
        WebDriverWait wait = new  WebDriverWait(driver,DEFAULT_TIMEOUT);
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//android.widget.TextView[@text='"+text+"']")));
        return driver.findElement(By.xpath("//android.widget.TextView[@text='"+text+"']"));
    }

    public WebElement findByText(String text,int index){
        WebDriverWait wait = new WebDriverWait(driver,DEFAULT_TIMEOUT);
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//android.widget.TextView[@text='"+text+"']")));
        return driver.findElements(By.xpath("//android.widget.TextView[@text='"+text+"']")).get(index);
    }

    public WebElement findByClassType(String className,int index){
        WebDriverWait wait = new WebDriverWait(driver,DEFAULT_TIMEOUT);
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.className(className)));
        return driver.findElements(By.className(className)).get(index);
    }

    //封装长按
    public void longClick(WebElement we){
        TouchAction action = new TouchAction(driver);
        action.longPress(we).perform().release();
    }

    public String getWebElementText(WebElement element){
        return element.getText();
    }

    public void click(WebElement we){
        we.click();
    }

    public void enterText(WebElement we, String text){
        we.sendKeys(text);
    }

    public void clear(WebElement we){
        we.clear();
    }

}
